package com.acooly.module.openapi.client.provider.newyl.utils;

import com.acooly.module.openapi.client.api.exception.ApiClientException;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringWriter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StringHelper {

    // 转换为标准格式（避免自闭合的问题）
     public static String asXml(Element body) {
         OutputFormat format = new OutputFormat();
         format.setEncoding("UTF-8");
         format.setExpandEmptyElements(true);
         StringWriter out = new StringWriter();
         XMLWriter writer = new XMLWriter(out, format);
         try {
             writer.write(body);
             writer.flush();
         } catch (IOException e) {
             log.info("XML转换为标准格式=>单闭合节点变双节点转换异常!");
             throw new ApiClientException("XML转换为标准格式=>单闭合节点变双节点转换异常!");
         }
         return out.toString();
     }

    /**
     * 将byte[] 转换成字符串
     *
     * @return
     */
    public static String byte2Hex(byte[] srcBytes) {
        StringBuilder hexRetSB = new StringBuilder();
        for (byte b : srcBytes) {
            String hexString = Integer.toHexString(0x00ff & b);
            hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
        }
        return hexRetSB.toString();
    }

    /**
     * 将16进制字符串转为转换成字符串
     *
     * @param source
     * @return
     */
    public static byte[] hex2Bytes(String source) {
        byte[] sourceBytes = new byte[source.length() / 2];
        for (int i = 0; i < sourceBytes.length; i++) {
            sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
        }
        return sourceBytes;
    }

    public static String nvl(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        return str.trim();
    }//method

}
